package com.jiegui.socket;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: wuqicheng
 * @time: 14/2/2023 下午 4:27
 */
@Data
@Component
public class DelongServerSocket {

    private static final Logger logger = LoggerFactory.getLogger("file-socket");
//    @Value("${socket.port}")
//    private Integer port;
    private boolean started;
    private ServerSocket ss;
    public static ConcurrentHashMap<String, ClientSocket> clientsMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, Date> ipMap = new ConcurrentHashMap<>();
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        logger.info("进入main:");
        new DelongServerSocket().start(8848);
    }

    public void start() {
        start(null);
    }

    public void start(Integer port) {
        try {
            ss = new ServerSocket(port == null ? 8848 : port);
            started = true;
            logger.info("端口已开启,占用端口号...."+8848);
        } catch (Exception e) {
            logger.info("端口使用中....");
            logger.info("请关掉相关程序并重新运行服务器！");
            e.printStackTrace();
            System.exit(0);
        }
        int count = 0;
        try {
            while (started) {
                Socket socket = ss.accept();
                socket.setKeepAlive(true);
                count++;
                ClientSocket register = ClientSocket.register(socket,count);
                logger.info("a client connected!");
                if (register != null) {
                    executorService.submit(register);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
